package com.sxt;

import java.util.Arrays;
import java.util.EmptyStackException;

/**自定义栈容器*/
public class MyStack01<E> {

    private Object[] arr1;//创建数组
    private int stackLength1 = 6;//数组的默认长度
    private int size;//记录栈容器的元素个数
    private int index = -1;//操作数组下标位置的指针

    //判断是否为空
    public boolean  empty(){
        return this.size == 0;
    }
    //添加元素
    public E push(E item){
        //初始化数组
        this.capacity();
        //向数组添加元素
        this.arr1[++index]=item;
        //记录元素，通过索引添加
        this.size++;
        return item;
    }
    //获取栈顶元素
    public E pop(){
        if(this.index==-1){
            throw new EmptyStackException();
        }
        this.size--;
        return (E) this.arr1[index--];
    }
    //数组初始化或者以1.5倍容量对数组扩容
    private void capacity(){
        //数组初始化
        if(this.arr1==null){
            this.arr1=new Object[this.stackLength1];
        }
        if(this.size-(this.stackLength1-1)>=0){
            this.stackLength1 = this.stackLength1+(this.stackLength1 >> 1);//右位移一位等于除以2
            this.arr1 = Arrays.copyOf(this.arr1,this.stackLength1);
        }
    }

    public static void main(String[] args) {
        MyStack01<String> myStack01 = new MyStack01<>();
        myStack01.push("a");
        myStack01.push("b");
        myStack01.push("c");
        myStack01.push("d");
        myStack01.push("e");
        myStack01.push("f");
        myStack01.push("g");
        myStack01.push("h");
        System.out.println(myStack01.size);
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
        System.out.println(myStack01.pop());
    }
}
